package com.chuanke.ckfamily.service.user.thread;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chuanke.ckfamily.dao.user.model.User;
import com.chuanke.ckfamily.service.common.WyService;
import com.chuanke.ckfamily.service.exception.CFException;
import com.chuanke.ckfamily.service.user.UserService;

public class WyFriendThread extends Thread{
	
	private static final Logger logger = LoggerFactory.getLogger(WyFriendThread.class);

	private Long uid ;
	
	private UserService userService;
	
	private WyService wyService;

	public WyFriendThread(Long uid, UserService userService, WyService wyService) {
		this.uid=uid;
		this.userService=userService;
		this.wyService=wyService;
	}

	@Override
	public void run() {
		try {
			logger.debug("异步更新网易云信好友关系===========>开始。uid={}",uid);
			
			//上级对我的备注
			User user = userService.findById(uid);
			if(user==null){
				return ;
			}
			
			Long super_id = user.getSuper_id();
			if(super_id!=null && super_id!=0 && !uid.equals(super_id) && StringUtils.isNotEmpty(user.getRemark_name())){
				User sUser = userService.findById(super_id);
				if(sUser!=null && sUser.hasWyId()){
					wyService.addFriend(sUser.getUser_no(), user.getUser_no());
					wyService.updateFriend(sUser.getUser_no(), user.getUser_no(), user.getRemark_name(), null);
				}
			}
			
			//下级对我的备注
			Map<String,Object> param=new HashMap<>();
			param.put("super_id", uid);
			List<User> list = userService.searchUser(param);
			if(list!=null && !list.isEmpty()){
				for (User u : list) {
					if(u.hasWyId() && StringUtils.isNotEmpty(u.getSuper_remark_name())){
						wyService.addFriend(u.getUser_no(), user.getUser_no());
						wyService.updateFriend(u.getUser_no(), user.getUser_no(), u.getSuper_remark_name(), null);
					}
				}
			}
			logger.debug("异步更新网易云信好友关系===========>结束。uid={}",uid);
		} catch (CFException e) {
			e.printStackTrace();
		}
	}
}
